const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      rules: {
        Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        End_Date: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
        Supplier_SerialNumber: [{ required: true, message: '请输入供应商流水号', trigger: 'blur' }],
      },
      supplier_info: [],
      article_info: [],
      isDisabled: true,
      specs: [],
      form: {     //采购价格单
        Purchase_Unit_Price_SerialNumber: "",  //主键
        Start_Date: '',
        End_Date: '',
        Supplier_SerialNumber: '',  // 供应商流水号
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          purchase_unitprice_detail: [{     //采购价格单明细
            Purchase_Unit_Price_Detail_SerialNumber: "",
            Purchase_Unit_Price_SerialNumber: '',
            Article_SerialNumber: '',  //商品流水号
            Article_Specifications_SerialNumber: '',  //商品规格流水号
            Unit_Price: '',   //吊牌价
            Purchase_Unit_Price: '',  //采购单价
            specs: [],
          }],
        }
      },
      loading: false,
      rules: {
        Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        End_Date: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
        Supplier_SerialNumber: [{ required: true, message: '请输入供应商流水号', trigger: 'blur' }],
      },
      Article_SerialNumber: [
        { required: true, message: '请选择商品', trigger: 'change' }
      ],
      Article_Specifications_SerialNumber: [
        { required: true, message: '请选择商品规格', trigger: 'change' }
      ],
      Unit_Price: [
        { required: true, message: '请输入零售价', trigger: 'blur' }
      ],
      Purchase_Unit_Price: [
        { required: true, message: '请输入采购单价', trigger: 'blur' }
      ]
    }
  },
  mounted() {
    let Purchase_Unit_Price_SerialNumber = sessionStorage.getItem("Purchase_Unit_Price_SerialNumber");
    console.log(Purchase_Unit_Price_SerialNumber);
    this.getList(Purchase_Unit_Price_SerialNumber)
    this.getData();
  },
  methods: {
    Change_Specifications_Name(index) {
      let str = this.form.Children.purchase_unitprice_detail[index].Article_Specifications_SerialNumber
      console.log(str)
      console.log(this.form.Children.purchase_unitprice_detail[index].specs[0])
      for (let i = 0; i < this.form.Children.purchase_unitprice_detail[index].specs.length; i++) {
        console.log(this.form.Children.purchase_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber)
        if (this.form.Children.purchase_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber == str) {
          // this.form.Children.purchase_unitprice_detail[index].Net_Content = this.form.Children.purchase_unitprice_detail[index].specs[i].Net_Content
          this.form.Children.purchase_unitprice_detail[index].Unit_Price = this.form.Children.purchase_unitprice_detail[index].specs[i].Unit_Price
        }
      }
    },
    Change_Unit_Price(index, e) {
      // this.isDisabled = true
      let str = this.form.Children.purchase_unitprice_detail[index].Article_SerialNumber
      this.form.Children.purchase_unitprice_detail[index].Article_Specifications_SerialNumber = ''
      let i = this.article_info.filter((item) => {
        return item.Article_SerialNumber == e
      })
      this.form.Children.purchase_unitprice_detail[index].Unit_Price = i[0].Unit_Price
      let _this = this;
      $.ajax({
        type: 'POST',
        url: DomainName + "/SpecificationsIDAction",
        data: {
          Article_SerialNumber: str,
          token: $.cookie("token")
        },
        success: function (res) {
          _this.form.Children.purchase_unitprice_detail[index].specs = res
          console.log(res)
          _this.isDisabled = false
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    getData() {
      let _this = this;
      $.ajax({
        url: DomainName + '/GoodsFileInquiry',
        type: 'POST',
        data: { Data: "supplier_info" },
        success: function (res) {
          _this.supplier_info = res
          console.log(_this.supplier_info)
        }
      })
      $.ajax({
        url: DomainName + '/getInquiryAction',
        type: 'POST',
        data: { token: $.cookie("token"), Data: 'article_info' },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status == '0'
          })
          _this.article_info = res
          console.log(_this.article_info)

        }
      })
    },
    getList(Purchase_Unit_Price_SerialNumber) {
      const _this = this
      $.ajax({
        type: 'POST',
        url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie("token"),
        data: {
          JSONObject: JSON.stringify({
            purchase_unitprice: { purchase_unitprice_detail: {} },
          }),
          Primary_Key: Purchase_Unit_Price_SerialNumber,
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        success: function (Result) {
          if (Result.Status == 'success') {
            console.log(Result);
            _this.form = Result.purchase_unitprice[0]
          }
        },
        dataType: "json"
      });
    },
    add_purchase_unitprice_detail() {
      this.form.Children.purchase_unitprice_detail.push({     //采购价格单
        Purchase_Unit_Price_Detail_SerialNumber: "",
        Purchase_Unit_Price_SerialNumber: this.form.Purchase_Unit_Price_SerialNumber,
        Article_SerialNumber: '',  //商品流水号
        Article_Specifications_SerialNumber: '',  //商品规格流水号
        Unit_Price: '',   //吊牌价
        Purchase_Unit_Price: '',  //采购单价
        specs: [],
      })
    },
    remove_purchase_unitprice_detail() {
      if (this.form.Children.purchase_unitprice_detail.filter(item => item.Row_Status != '1').length > 0) {
        let i = this.form.Children.purchase_unitprice_detail.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.purchase_unitprice_detail.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.purchase_unitprice_detail.pop()
        } else {
          this.$confirm('警告！此操作将删除一条适用企业, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.purchase_unitprice_detail.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //记得更改主表名
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const _this = this
          _this.loading = true
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { purchase_unitprice: [modify] } }) }
          } else {
            data = {
              Data: JSON.stringify(
                {
                  Modify: { purchase_unitprice: [modify] },
                  Add: { purchase_unitprice: [add] }
                }
              ),
            }
          }
          $.ajax({
            url: DomainName + '/getEditAction?token=' + $.cookie("token"),
            type: 'POST',
            data,
            success: function (res) {
              console.log('提交结果', res)
              _this.$message.success("提交成功")
              window.history.go(-1);
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        }

      })
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_purchase_unitprice_detail = [], modify_purchase_unitprice_detail = []
      for (const i in modify.Children.purchase_unitprice_detail) {
        const obj = modify.Children.purchase_unitprice_detail[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_purchase_unitprice_detail.push(obj)
        } else {
          modify_purchase_unitprice_detail.push(obj)
        }
      }
      add.Children.purchase_unitprice_detail = add_purchase_unitprice_detail

      modify.Children.purchase_unitprice_detail = modify_purchase_unitprice_detail

      if (add_purchase_unitprice_detail.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
  }
})